//
//  ZDBSubimtTaskViewController.m
//  ZDB
//
//  Created by Kk on 2020/4/4.
//  Copyright © 2020 ZDB. All rights reserved.
//

#import "ZDBSubimtTaskViewController.h"

@interface ZDBSubimtTaskViewController ()
@property(strong,nonatomic)NSString * kUploadIconImageToken;
@property(strong,nonatomic)UIImage * selectImage;
@end

@implementation ZDBSubimtTaskViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getModel:_model];
   
     [self getAvatarQiniuToken];
    [_submitBtn add_BtnClickHandler:^(NSInteger tag) {//上传截图
        [self uploadWXImage];
    }];
    [_addImageBtn add_BtnClickHandler:^(NSInteger tag) {
        [self addTapAction];
    }];
}
- (void)addTapAction
{
     [self uploadImage];
}
- (void)uploadWXImage
{
    if (!_selectImage)
    {
        [JMNotifyView showNotify:@"请上传微信截图" isSuccessful:NO];
        return;
    }
    if (self.kUploadIconImageToken)
    {
        self.submitBtn.userInteractionEnabled = NO;
        [self showLoadingAnimation];
        WeakSelf
        [self upLoadImageToQINiu:weakSelf.selectImage andBlock:^(NSString *imageKey) {
            NSLog(@"imageKey----%@",imageKey);
            
            NSMutableDictionary * diccc = [NSMutableDictionary dictionary];
            [diccc setValue:weakSelf.id forKey:@"id"];
             [diccc setValue:imageKey forKey:@"images"];
            
            WeakSelf
            NSString  * submitTaskRegisterTask = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"userSubmitTaskInfo"];
            [[SmileHttpTool sharedInstance] POST:submitTaskRegisterTask parameters:diccc origin:NO success:^(NSInteger statusCode, NSString *message, id responseObject) {
                [self stopLoadingAnimation];
                if (statusCode ==0) {
                    [JMNotifyView showNotify:@"提交任务材料等待审核" isSuccessful:NO];
              
                    if (weakSelf.updetaTaskBlock) {
                        weakSelf.updetaTaskBlock(YES);
                    }
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }else
                {
                    [JMNotifyView showNotify:message isSuccessful:NO];;
                }
                
                self.submitBtn.userInteractionEnabled = YES;
            } failure:^(id responseObject, NSError *error) {
                [self stopLoadingAnimation];
            }];
        }];
    }else
    {
        [self getAvatarQiniuToken];
    }
}

// 上传照片
- (void)uploadImage {
   
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.allowPickingGif = NO;
    if (@available(iOS 13.0, *)) {
        imagePickerVc.statusBarStyle = UIStatusBarStyleDarkContent;
    } else {
        imagePickerVc.statusBarStyle = UIStatusBarStyleDefault;
        
    }
    imagePickerVc.alwaysEnableDoneBtn = YES;
    imagePickerVc.allowPickingVideo = NO; //不许选择视频
    imagePickerVc.allowPickingMultipleVideo = NO;//不允许选择视频gif
    imagePickerVc.barItemTextColor = [UIColor colorWithHexString:@"#333333"];
    imagePickerVc.naviTitleColor = [UIColor colorWithHexString:@"#333333"];
    [imagePickerVc setPhotoPickerPageUIConfigBlock:^(UICollectionView *collectionView, UIView *bottomToolBar, UIButton *previewButton, UIButton *originalPhotoButton, UILabel *originalPhotoLabel, UIButton *doneButton, UIImageView *numberImageView, UILabel *numberLabel, UIView *divideLine) {
        [doneButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    }];
    WeakSelf
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count >0) {
            weakSelf.selectImage =photos.firstObject;
            [self.addImageBtn setBackgroundImage:weakSelf.selectImage forState:0];
            
        }
        
    }];
    imagePickerVc.modalPresentationStyle = 0;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark -- 上传封面到七牛
-(void)upLoadImageToQINiu:(UIImage *)coverImg andBlock:(void (^)(NSString  *))imageBackBlock{
    
    if (self.kUploadIconImageToken) {
        
        NSData *data =UIImageJPEGRepresentation(coverImg, 0.8);
        
        QNUploadManager *upManager = [[QNUploadManager alloc] init];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *key = [NSString stringWithFormat:@"iOS%@.jpg", [formatter stringFromDate:[NSDate date]]];
        [upManager putData:data key:key token:self.kUploadIconImageToken
                  complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                      if (!kDictIsEmpty(resp)) {
                          !imageBackBlock ? : imageBackBlock([resp jsonString:@"key"]);
                      }else
                      {
                           [self stopLoadingAnimation];
                            self.submitBtn.userInteractionEnabled = YES;
                           [JMNotifyView showNotify:@"上传照片失败" isSuccessful:NO];
                      }
                  } option:nil];
    }else{
        [self getAvatarQiniuToken];
    }
}
//获取七牛头像token
-(void)getAvatarQiniuToken{
    [self showLoadingAnimation];
    WEAKSELF
    [[SmileHttpTool sharedInstance] getTokenFromQiNiu:@"" resultBlock:^(BOOL isSuccess, NSString *token) {
        [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf)
        if (isSuccess) {
            strongSelf.kUploadIconImageToken = token;
        }
    }];
}
- (void)getModel:(ZDBTastModel *)model
{
//    [_icon sd_setImageWithURL:[NSURL URLWithString:model.taskUrl] placeholderImage:PlaceHolderImage];
    [_icon sd_setImageWithURL:[NSURL URLWithString:model.taskUrl] placeholderImage:[UIImage imageNamed:@"renwunoon"]];
    switch (model.state.integerValue) {//任务状态 1=进行中 2=审核中 3=已完成 4=已过期
        case 1:
            _taskStatus.text = kFormat(@"任务状态：%@", @"进行中");
            break;
        case 2:
            _taskStatus.text = kFormat(@"任务状态：%@", @"审核中");
            break;
        case 3:
            _taskStatus.text = kFormat(@"任务状态：%@", @"已完成");
            break;
        case 4:
            _taskStatus.text = kFormat(@"任务状态：%@", @"已过期");
            break;
        default:
            break;
    }
    _time.text = kFormat(@"领取时间：%@", kStringIsEmpty(_model.receiveTime)?@"":_model.receiveTime);
    NSString * price = kFormat(@" ¥%@", model.money);
    NSString * integral = kFormat(@" %@", model.integral);
    _price.attributedText = [ZBDUnit getcontent:price image:@"coins" index:0 imageframe:CGRectMake(0, -3, 16, 16)];
    _integralLab.attributedText = [ZBDUnit getcontent:integral image:@"jifen" index:0 imageframe:CGRectMake(0, -1, 12, 12)];
    
    
}
@end
